let curUnionID = null;
let curUid = null;

let curDetail = null;

function createList(pageNo = 1, pageSize = 10) {

    let matchData = {};

    let curUid = $("#txtSearch").val();
    if (curUid) {
        matchData.uid = curUid;
    }
    //matchData["unionID"] = curUnionID;

    var start = (pageNo - 1) * pageSize;
    apiAdminGetRecord("userTargetModel", start, pageSize, matchData, function (data) {
        if (data.code === 0) {
            if (data.code === 0) {
                setTimeout(() => {
                    data.msg.recordArr.sort((a, b) => b.createTime - a.createTime);
                    $('#dataList').bootstrapTable('load', data.msg);
                }, 200)

            }
        }
    });
}

function addAccountShow() {

    $("#addUserUID").val('');
    $("#addUserBets").val('');
    $("#addUserScore").val('');
    $('#addAccount').modal('show');
}

//新增账号
function addAccount() {

    let unionID = $("#addUserUID").val() || 1;
    let maxBureau = $("#addUserBets").val();
    let score = $("#addUserScore").val();
    let gameType = $("#addGameType").val();


    if (unionID && maxBureau && score) {

        let uid = curUid;
        let createTime = Date.now();
        apiAdminAddRecord('userTargetModel', { createTime, gameType, unionID, uid, maxBureau, score }, function (data) {

            if (data.code != 0) {
                Swal.fire('新增失败');
            } else {
                $('#addAccount').modal('hide');
                $.modal({ body: '新增成功' });
                createList(1);
            }
        })
    }
}


function onTargetEnd(id) {


    Swal.fire({
        title: '确定要终止任务奖励？',
        text: "终止任务后无法恢复，请谨慎操作",
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#198754',
        cancelButtonColor: '#d93444',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
    }).then((result) => {
        if (result.isConfirmed) {
            apiAdminDeleteRecord('userTargetModel', { '_id': id }, function (data) {

                if (data.code != 0) {
                    Swal.fire('更新失败');
                } else {
                    $.modal({ body: '更新成功' });
                    var currentPage = $('#robotData').bootstrapTable('getOptions').pageNumber
                    createList(currentPage);
                }
            })
        }
    });





}

//详情
function onDetail(curData) {

    // curData = JSON.parse(curData);
    $('#scoreList').bootstrapTable('destroy');
    //数据表格初始化
    $('#scoreList').bootstrapTable({
        showRefresh: true,
        striped: true, // 是否显示行间隔色
        pageNumber: 1, // 初始化加载第一页
        pagination: true, // 是否分页
        sidePagination: 'client', // server:服务器端分页|client：前端分页
        pageSize: 10, // 单页记录数
        pageList: [10, 20, 30],
        theadClasses: "thead-light", //这里设置表头样式
        smartDisplay: false,
        buttonsClass: 'light',
        buttonsPrefix: 'btn',
        data: curData,
        maintainSelected: true,
        showRefresh: false, // 刷新按钮
        onPageChange: function (number, size) {
            // createList(number, size);
        },
        // createTime: Date.now(), score, beforScore, winScore, userScore, userType
        queryParams: function (params) { },
        columns: [
            {
                title: '起始分数',
                align: "center",
                valign: "middle",
                field: 'beforScore',
            },
            {
                title: '输赢分数',
                align: "center",
                valign: "middle",
                field: 'winScore',
            },
            {
                title: '总输赢',
                align: "center",
                valign: "middle",
                field: 'userScore',
            },
            {
                title: '目标分数',
                align: "center",
                valign: "middle",
                field: 'score',
            },
            {
                title: '控制类型',
                align: "center",
                valign: "middle",
                field: 'userType',
                formatter: typeMatter
            },
            {
                title: '时间',
                align: "center",
                valign: "middle",
                field: 'createTime',
                formatter: dateMatter
            }
        ]
    });
    $('#scoreDetail').modal('show');


}


function typeMatter(value, row, index) {
    if (value == 5) {
        return '强制';
    }
    else if (value == 4) {
        return '高级';
    }
    else if (value == 3) {
        return '中级';
    }
    else if (value == 2) {
        return '初级';
    } else if (value == 1) {
        return '输';
    }
}




$(document).ready(function () {
    var parameters = parseQueryString(window.location.href);
    //curUnionID = parameters.unionID;
    curUid = parameters.uid;
    //数据表格初始化
    $('#dataList').bootstrapTable({
        showRefresh: true,
        striped: true, // 是否显示行间隔色
        pageNumber: 1, // 初始化加载第一页
        pagination: true, // 是否分页
        sidePagination: 'server', // server:服务器端分页|client：前端分页
        pageSize: 10, // 单页记录数
        pageList: [10, 20, 30],
        theadClasses: "thead-light", //这里设置表头样式
        totalField: "totalCount",
        smartDisplay: false,
        buttonsClass: 'light',
        buttonsPrefix: 'btn',
        dataField: "recordArr",
        maintainSelected: true,
        showRefresh: false, // 刷新按钮
        onPageChange: function (number, size) {
            createList(number, size);
        },
        queryParams: function (params) { // 上传服务器的参数
            var temp = { //如果是在服务器端实现分页，limit、offset这两个参数是必须的
                limit: params.limit, // 每页显示数量
                offset: params.offset, // SQL语句起始索引
            };
            return temp;
        },
        columns: [{
            title: 'id',
            field: '_id',
            visible: false
        },
        {
            title: '联盟ID',
            align: "center",
            valign: "middle",
            field: 'unionID',
        },
        {
            title: '玩家ID',
            align: "center",
            valign: "middle",
            field: 'uid',
        },
        {
            title: '游戏类型',
            align: "center",
            valign: "middle",
            field: 'gameType',
            formatter: gameTypeMatter
        },
        {
            title: '目标局数',
            align: "center",
            valign: "middle",
            field: 'maxBureau',
        },
        {
            title: '当前局数',
            align: "center",
            valign: "middle",
            field: 'curBureau',
        },
        {
            title: '目标分数',
            align: "center",
            valign: "middle",
            field: 'score',
        },
        {
            title: '最终分数',
            align: "center",
            valign: "middle",
            field: 'endScore',
            // formatter: scoreMatter
        },
        {
            title: '是否结束',
            align: "center",
            valign: "middle",
            field: 'endTime',
            formatter: endMatter
        },
        {
            title: '结束时间',
            align: "center",
            valign: "middle",
            field: 'endTime',
            formatter: dateMatter
        },
        {
            title: '创建时间',
            align: "center",
            valign: "middle",
            field: 'createTime',
            formatter: dateMatter
        },
        {
            title: '操作',
            width: 100,
            align: "center",
            valign: "middle",
            formatter: option
        }

        ]
    });
    $('#dataList').bootstrapTable('hideLoading');
    createList(1);
});


// 定义删除、更新按钮
function option(value, row, index) {
    var htm = "";
    htm += `<button type="button" class="btn btn-light"  data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="执行详情" onClick='onDetail(${JSON.stringify(row.detail)})'><i class="bi bi-eye-fill fs-5 text-success"></i></button>`;
    if (true) {
        htm += `<button type="button" class="btn btn-light mx-1"  data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="取消" onClick='onTargetEnd(${JSON.stringify(row._id)})'><i class="bi bi-x-octagon-fill fs-5 text-danger"></i></button>`;
    }

    return htm;
}

function endMatter(value, row, index) {
    if (value) {
        return '已结束';
    }
}

function dateMatter(value, row, index) {
    if (value) {
        return new Date(parseInt(value)).toLocaleString();
    }
}

function scoreMatter(value, row, index) {
    if (value) {
        return '<span class = "text-primary" >' + value + '</span>'
    } else {
        return 0;
    }

}

function gameTypeMatter(value, row, index) {

    if (value >= 1) {
        return enumeration.gameName[value]
    }
    else {
        return "其他"
    }

}

function changeTypeMatter(value, row, index) {
    if (value === enumeration.scoreChangeType.GIVE) {
        return "赠送分数";
    } else if (value === enumeration.scoreChangeType.MODIFY_LOW) {
        return "给下级改分";
    } else if (value === enumeration.scoreChangeType.MODIFY_UP) {
        return "被上级改分";
    } else if (value === enumeration.scoreChangeType.GAME_WIN) {
        return "赢分";
    } else if (value === enumeration.scoreChangeType.GAME_START_UNION_CHOU) {
        return "门票";
    } else if (value === enumeration.scoreChangeType.GAME_WIN_CHOU) {
        return "赢家抽分";
    } else if (value === enumeration.scoreChangeType.SAFE_BOX) {
        return "返利提取";
    } else if (value === enumeration.scoreChangeType.UNION_SERVICE) {
        return "联盟服务费";
    } else if (value === enumeration.scoreChangeType.FIX_SCORE) {
        return "保底";
    } else if (value === enumeration.scoreChangeType.SAVE_BOX) {
        return "保险柜操作";
    }
}